
local module = _G["BlinkHealthTextModule"]

if select(2, UnitClass("player")) ~= "DEATHKNIGHT" or not module then return end

local tcopy
local loaded = false
local RUNETYPE_BLOOD = 1
local RUNETYPE_UNHOLY = 2
local RUNETYPE_FROST = 3
local RUNETYPE_DEATH = 4
local iconTextures = {}
iconTextures[RUNETYPE_BLOOD] = "Interface\\PlayerFrame\\UI-PlayerFrame-Deathknight-Blood"
iconTextures[RUNETYPE_UNHOLY] = "Interface\\PlayerFrame\\UI-PlayerFrame-Deathknight-Unholy"
iconTextures[RUNETYPE_FROST] = "Interface\\PlayerFrame\\UI-PlayerFrame-Deathknight-Frost"
iconTextures[RUNETYPE_DEATH] = "Interface\\PlayerFrame\\UI-PlayerFrame-Deathknight-Death"

local L_DEATH_TRANCE = "죽음의 무아지경"
local L_RUNE_STRIKE = "룬의 일격"
local L_HORN_OF_WINTER = "겨울의 뿔피리"
local L_FROZEN_SOLID = "혹한의 안개"
local L_FREEZING_FOG = "단단한 얼음"
local L_KILLING_MACHINE = "도살기"
local L_STRENGTH_OF_EARTH = "대지력"
local L_SUDDEN_DOOM = "불시의 파멸"
local L_CRISMON_SCOURGE = "진홍빛 스컬지"
local L_DK_CONFIG = "죽음의 기사 설정"
local L_USE_RUNE = "룬 보유 상태를 숫자와 색상으로 표시합니다."
local L_USE_DISEASE = "|TInterface\\Icons\\Spell_Deathknight_Frostfever:20|t서리열병(플레이어 체력옆)과 |TInterface\\Icons\\Spell_Deathknight_Bloodplague:20|t피의 역병(대상 체력옆)의 남은 시간을 표시합니다."
local L_USE_CRISMON_SCOURGE = "|TInterface\\Icons\\Spell_Deathknight_Bloodboil:20|t진홍빛 스컬지 발동 아이콘을 표시합니다."
local L_USE_SUDDEN_DOOM = "|TInterface\\Icons\\Spell_Shadow_Painspike:20|t불시의 파멸 효과가 발동하면 |TInterface\\Icons\\Spell_Shadow_Deathcoil:20|t죽음의 고리 아이콘을 표시합니다."


local text
local name, rank, icon, count, debufType, duration, expirationTime
local size
local usable, nomana
local aCount
local diseaseUpdator

local defaultDB = {
	db_ver = 1.0,
	use_rune = true,
	use_disease = true,
	use_crismon_scourge = true,
}

module.config = {
	[L_KILLING_MACHINE] = {
		spellid = 51128
	},
	[L_FREEZING_FOG] = {
		spellid = 59057
	},
	[L_CRISMON_SCOURGE] = {
		spellid = 81136,
	},
	[L_SUDDEN_DOOM] = {
		spellid = 49530,
	},
	--[] = {3, 28, false},
}

-------------------------------------------------------------------------------
-- local functions
-------------------------------------------------------------------------------

function tcopy(to, from) -- "to" must be a table (possibly empty)
	for k,v in pairs(from) do
		if(type(v)=="table") then
			if not to then to = {} end
			to[k] = {}
			tcopy(to[k], v)
		else
			to[k] = v
		end
	end
end

local function getSize(baseSize, expirationTime, duration)
	local size = (expirationTime-GetTime()) / duration
	if size < 0.3 then
		size = baseSize * .8
	elseif size < 0.6 then
		size = baseSize * 1.0
	else
		size = baseSize * 1.2
	end
	return size / 2
end


-------------------------------------------------------------------------------
-- module functions
-------------------------------------------------------------------------------

function module:init()

	if self.addon.db then
		if not self.addon.db.class or not self.addon.db.class.db_ver or self.addon.db.class.db_ver < defaultDB.db_ver then
			self.addon.db.class = {}
			tcopy(self.addon.db.class, defaultDB)
		end
	end

	self.addon.mainFrame:RegisterEvent("PLAYER_ALIVE")
	self.addon.mainFrame:RegisterEvent("LEARNED_SPELL_IN_TAB")
	self.addon.mainFrame:RegisterEvent("CHARACTER_POINTS_CHANGED")

	if self.addon.db.class.use_rune then
		self:EnableRune()
	end

	if self.addon.db.class.use_disease then
		self:EnableDisease()
	end

	self:update()

	if loaded==false then
		self:AddMiscConfig{
			type = "description",
			text = L_DK_CONFIG,
			fontobject = "QuestTitleFont",
			r = 1,
			g = 0.82,
			b = 0,
			justifyH = "LEFT",
		}
		self:AddMiscConfig{
			type = "toggle",
			text = L_USE_RUNE,
			tooltip = L_USE_RUNE,
			get = function ()
				return module.addon.db.class.use_rune
			end,
			set = function (value)
				module.addon.db.class.use_rune = value
				if module.addon.db.class.use_rune then
					module:EnableRune()
				else
					module:DisableRune()
				end
			end,
		}
		self:AddMiscConfig{
			type = "toggle",
			text = L_USE_DISEASE,
			tooltip = L_USE_DISEASE,
			get = function ()
				return module.addon.db.class.use_disease
			end,
			set = function (value)
				module.addon.db.class.use_disease = value
				if module.addon.db.class.use_disease then
					module:EnableDisease()
				else
					module:DisableDisease()
				end
			end,
		}
		self:AddMiscConfig{
			type = "toggle",
			text = L_USE_CRISMON_SCOURGE,
			tooltip = L_USE_CRISMON_SCOURGE,
			get = function ()
				return module.addon.db.class.use_crismon_scourge
			end,
			set = function (value)
				module.addon.db.class.use_crismon_scourge = value
			end,
		}
		self:AddMiscConfig{
			type = "toggle",
			text = L_USE_SUDDEN_DOOM,
			tooltip = L_USE_SUDDEN_DOOM,
			get = function ()
				return module.addon.db.class.use_sudden_doom
			end,
			set = function (value)
				module.addon.db.class.use_sudden_doom = value
			end,
		}
		loaded = true
	end
end

function module:update()
	self.primary = GetSpecialization()
	for auraName, t in pairs(self.config) do
		if t.talent and t.talent > 0 then
			local name, iconTexture, tier, column, selected, available = GetTalentInfo(t.talent);
			if name and available then
				self.config[auraName].use = true
				if t.event and self.addon and self.addon.mainFrame then
					self.addon.mainFrame:RegisterEvent(t.event)
				end
			end
		else
			self.config[auraName].use = false
			if IsPlayerSpell(t.spellid) then
				self.config[auraName].use = true
				if t.event and self.addon and self.addon.mainFrame then
					self.addon.mainFrame:RegisterEvent(t.event)
				end
			end
		end
	end
end

function module:LEARNED_SPELL_IN_TAB(...)
	self:update()
end
module.CHARACTER_POINTS_CHANGED = module.LEARNED_SPELL_IN_TAB
function module:PLAYER_ALIVE(...)
	self.addon.mainFrame:UnregisterEvent("PLAYER_ALIVE")
	self:update()
end

function module:RUNE_POWER_UPDATE(...)
	self:updateRunes()
end
module.RUNE_TYPE_UPDATE = module.RUNE_POWER_UPDATE
--module.PLAYER_REGEN_DISABLED = module.RUNE_POWER_UPDATE

function module:getAuraTypeCount(unit, auraType, filter)
	if not UnitExists(unit) then return end

	local i = 1
	aCount = 0

	name, rank, icon, count, debufType, duration, expirationTime = UnitAura(unit, i, filter)
	while name do
		if debufType == auraType then
			if count > 0 then
				aCount = aCount + count
			else
				aCount = aCount + 1
			end
		end
		i = i + 1
		name, rank, icon, count, debufType, duration, expirationTime = UnitAura(unit, i, filter)
	end
	return aCount
end

function module:EnableRune()
	if not self.addon.playerFrame.runes then
		self.addon.playerFrame.runes = self.addon.playerFrame:CreateFontString(nil, "OVERLAY")
		self.addon.playerFrame.runes:SetFont(self.addon.db.font, self.addon.db.fontSizePower, self.addon.db.fontOutline)
		self.addon.playerFrame.runes:SetPoint("BOTTOM", self.addon.playerFrame.health, "TOP")
		self.addon.playerFrame.runes:SetAlpha(self.addon.db.unit.player.alpha)
		self.addon.playerFrame.runes:SetJustifyH("CENTER")
	end
	self.addon.playerFrame.runes:Show()
	self.addon.mainFrame:RegisterEvent("RUNE_POWER_UPDATE")
	self.addon.mainFrame:RegisterEvent("RUNE_TYPE_UPDATE")
end

function module:DisableRune()
	if self.addon.playerFrame.runes then
		self.addon.playerFrame.runes:Hide()
	end
	self.addon.mainFrame:UnregisterEvent("RUNE_POWER_UPDATE")
	self.addon.mainFrame:UnregisterEvent("RUNE_TYPE_UPDATE")
end

function module:EnableDisease()
	--print("EnableDisease")
	if not self.addon.playerFrame.disease then
		self.addon.playerFrame.disease = self.addon.playerFrame:CreateFontString(nil, "OVERLAY")
		self.addon.playerFrame.disease:SetFont(self.addon.db.font, self.addon.db.fontSizePower, self.addon.db.fontOutline)
		self.addon.playerFrame.disease:SetPoint("LEFT", self.addon.playerFrame.health, "RIGHT")
		self.addon.playerFrame.disease:SetAlpha(self.addon.db.unit.player.alpha)
		self.addon.playerFrame.disease:SetJustifyH("LEFT")
		self.addon.playerFrame.disease:SetTextColor(0.25, 0.25, 1.0)
	end
	self.addon.playerFrame.disease:Show()

	if not self.addon.targetFrame.disease then
		self.addon.targetFrame.disease = self.addon.targetFrame:CreateFontString(nil, "OVERLAY")
		self.addon.targetFrame.disease:SetFont(self.addon.db.font, self.addon.db.fontSizePower, self.addon.db.fontOutline)
		self.addon.targetFrame.disease:SetPoint("RIGHT", self.addon.targetFrame.health, "LEFT")
		self.addon.targetFrame.disease:SetAlpha(self.addon.db.unit.player.alpha)
		self.addon.targetFrame.disease:SetJustifyH("RIGHT")
		self.addon.targetFrame.disease:SetTextColor(0.25, 1.0, 0.25)
	end
	self.addon.targetFrame.disease:Show()

	self:RegisterUpdators(diseaseUpdator, self.addon.playerFrame.disease, self.addon.targetFrame.disease)
end

function module:DisableDisease()
	if self.addon.playerFrame.disease then
		self.addon.playerFrame.disease:Hide()
	end
	if self.addon.targetFrame.disease then
		self.addon.targetFrame.disease:Hide()
	end
	self:UnregisterUpdators(diseaseUpdator)
end

function module:getTargetText()
	text = ""
	size = self.addon.db.fontSizeHealth

	if self.config[L_CRISMON_SCOURGE].use and self.addon.db.class.use_crismon_scourge then
		name, rank, icon, count, debufType, duration, expirationTime = UnitAura("player", L_CRISMON_SCOURGE, nil, "HELPFUL")
		if name then
			size = getSize(self.addon.db.fontSizeHealth, expirationTime, duration)
			text = text .. (":|TInterface\\Icons\\Spell_Deathknight_Bloodboil:%d|t"):format(size)
		end
	end

	if self.config[L_SUDDEN_DOOM].use and self.addon.db.class.use_sudden_doom then
		name, rank, icon, count, debufType, duration, expirationTime = UnitAura("player", L_SUDDEN_DOOM, nil, "HELPFUL")
		if name then
			size = getSize(self.addon.db.fontSizeHealth, expirationTime, duration)
			text = text .. (":|TInterface\\Icons\\Spell_Shadow_Deathcoil:%d|t"):format(size)
		end
	end

	if self.config[L_KILLING_MACHINE].use then
		name, rank, icon, count, debufType, duration, expirationTime = UnitAura("player", L_KILLING_MACHINE, nil, "HELPFUL")
		if name then
			size = getSize(self.addon.db.fontSizeHealth, expirationTime, duration)
			text = text .. (":|T%s:%d|t"):format(icon, size)
		end
	end

	if self.config[L_FREEZING_FOG].use then
		name, rank, icon, count, debufType, duration, expirationTime = UnitAura("player", L_FROZEN_SOLID, nil, "HELPFUL")
		if name then
			size = getSize(self.addon.db.fontSizeHealth, expirationTime, duration)
			text = text .. (":|T%s:%d|t"):format(icon, size)
		end
	end

--	-- rune strike
--	usable, nomana = IsUsableSpell(L_RUNE_STRIKE)
--	_, _, icon = GetSpellInfo(L_RUNE_STRIKE)
--	if usable then
--		size = self.addon.db.fontSizeHealth * 1.2 / 2
--		text = text .. (":|T%s:%d|t"):format(icon, size)
--	end

--	-- horn of winter
--	if UnitLevel("player")>=65 and not UnitAura("player", L_HORN_OF_WINTER, nil, "HELPFUL") and not UnitAura("player", L_STRENGTH_OF_EARTH, nil, "HELPFUL") then
--		size = self.addon.db.fontSizeHealth * 1.2 / 2
--		--text = text .. (":|T%s:%d:%d:0:0|t"):format("Interface\\Icons\\INV_Misc_Horn_02", size, size)
--		text = text .. (":|T%s:%d|t"):format("Interface\\Icons\\INV_Misc_Horn_02", size)
--	end

	return text
end

local runes = {0,0,0,0}
function module:updateRunes()
	local text = ""
	local runeReady, runeType
	runes = {0,0,0,0}
	for k, i in pairs {1, 2, 5, 6, 3, 4} do -- 머야;;; 순서대로 해도되는건데...
		_, _, runeReady = GetRuneCooldown(i)
		runeType = GetRuneType(i)
		if runeType then
			if runeReady then
				runes[runeType] = runes[runeType] + 1
			end
		end
	end
	text = ("|cff%02x%02x%02x%d|r|cff%02x%02x%02x%d|r|cff%02x%02x%02x%d|r|cff%02x%02x%02x%d|r"):format(
		255, 63, 63, runes[RUNETYPE_BLOOD],
		63, 63, 255, runes[RUNETYPE_FROST],
		63, 255, 63, runes[RUNETYPE_UNHOLY],
		255, 63, 255, runes[RUNETYPE_DEATH])
	self.addon.playerFrame.runes:SetText(text)
end

function diseaseUpdator(unit, f1, f2)
	if not UnitExists("target") then
		f1:SetText("")
		f2:SetText("")
		return
	end

	local now, leftTime = GetTime(), 0
	--local name, _, _, _, _, duration, expirationTime = module:getAuraInfo("target", "", "PLAYER|HARMFUL")
	local name, _, _, _, _, duration, expirationTime = UnitAura("target", "서리 열병", nil, "PLAYER|HARMFUL")
	if name then
		leftTime = expirationTime - now
		if leftTime > 0 then
			f1:SetText( ("%d"):format(leftTime) )
		else
			f1:SetText("")
		end
	end

	name, _, _, _, _, duration, expirationTime = UnitAura("target", "피의 역병", nil, "PLAYER|HARMFUL")
	if name then
		leftTime = expirationTime - now
		if leftTime > 0 then
			f2:SetText( ("%d"):format(leftTime) )
		else
			f2:SetText("")
		end
	end
end
